// 平滑滚动效果
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();
        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth'
        });
    });
});

// 导航栏滚动效果
window.addEventListener('scroll', function() {
    const header = document.querySelector('header');
    if (window.scrollY > 50) {
        header.style.backgroundColor = 'rgba(44, 62, 80, 0.9)';
    } else {
        header.style.backgroundColor = '#2c3e50';
    }
});

// 轮播图功能
let slideIndex = 1;
showSlides(slideIndex);

function changeSlide(n) {
    showSlides(slideIndex += n);
}

function currentSlide(n) {
    showSlides(slideIndex = n);
}

function showSlides(n) {
    let i;
    let slides = document.getElementsByClassName("slides");
    let dots = document.getElementsByClassName("dot");
    
    if (n > slides.length) {slideIndex = 1}    
    if (n < 1) {slideIndex = slides.length}
    
    for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none";  
    }
    for (i = 0; i < dots.length; i++) {
        dots[i].className = dots[i].className.replace(" active", "");
    }
    
    slides[slideIndex-1].style.display = "block";  
    dots[slideIndex-1].className += " active";
}

// 自动轮播
setInterval(() => {
    changeSlide(1);
}, 5000);

// 菜单控制
function toggleMenu() {
    document.body.classList.toggle('menu-open');
}

// 点击链接后自动关闭菜单
document.querySelectorAll('nav a').forEach(link => {
    link.addEventListener('click', function(e) {
        // 保持原有的平滑滚动效果
        e.preventDefault();
        const targetId = this.getAttribute('href');
        document.querySelector(targetId).scrollIntoView({
            behavior: 'smooth'
        });
        
        // 延迟一下再关闭菜单，让用户看到点击效果
        setTimeout(() => {
            toggleMenu();
        }, 300);
    });
});

// 处理滑动手势
let touchStartX = 0;
let touchEndX = 0;

document.addEventListener('touchstart', e => {
    touchStartX = e.changedTouches[0].screenX;
});

document.addEventListener('touchend', e => {
    touchEndX = e.changedTouches[0].screenX;
    handleSwipeMenu();
});

function handleSwipeMenu() {
    const swipeThreshold = 50;
    const diff = touchEndX - touchStartX;

    if (Math.abs(diff) > swipeThreshold) {
        if (diff > 0 && !document.body.classList.contains('menu-open')) {
            // 向右滑动，打开菜单
            toggleMenu();
        } else if (diff < 0 && document.body.classList.contains('menu-open')) {
            // 向左滑动，关闭菜单
            toggleMenu();
        }
    }
} 